package cn.wp.common.core.dao;

import java.util.Iterator;

/**
 * 构建Sql语句
 * Created by chenyb on 2019/09/29
 */
public class SqlString {

    private StringBuilder stringBuilder = new StringBuilder();

    public static SqlString newInstance(){
        return new SqlString();
    }

    public SqlString add(String str){
        stringBuilder.append(" " + str + " ");
        return this;
    }

    public String build(){
        return stringBuilder.toString();
    }

    public String build(OLock optimisticLock){
        this.add("update");
        this.add(optimisticLock.getTable());
        int index = 0;
        Iterator<String> iterator = optimisticLock.getSetColumns().iterator();
        while(iterator.hasNext()){
            if(index > 0){
                this.add(",");
            }
            index++;
            this.add(iterator.next());
        }
        this.add(", set " + optimisticLock.getLockColumn() + " = " + optimisticLock.getLockColumn() + " + 1");

        Iterator<String> iteratorCondition = optimisticLock.getConditions().iterator();
        int conditionIndex = 0;
        while(iteratorCondition.hasNext()){
            if(index == 0){
                this.add("");
            }
            conditionIndex++;
            this.add(iteratorCondition.next());
        }

        this.add("and " + optimisticLock.getLockColumn() + " = ?");

        return stringBuilder.toString();
    }

    @Override
    public String toString() {
        return this.build();
    }

    public static void main(String[] args) {
        OLock oLock = new OLock();
        oLock.table("account").set("set balance = balance - 1").and("where id = 1");
        String sqlString = SqlString.newInstance().build(oLock);
        System.err.println(sqlString);
    }

}
